package com.winning.bdu.dl.quartz.base;

import com.winning.bdu.dl.quartz.manage.mapper.JobMonitorMapper;
import com.winning.bdu.dl.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

/**
 * @Author: shipengfei
 * @Description:
 * @Date: 2019-06-03 17:20
 */
@Slf4j
public abstract class BaseJob extends QuartzJobBean {


    @Autowired
    private JobMonitorMapper monitorMapper;

    /**
     * Execute the actual job. The job data map will already have been
     * applied as bean property values by execute. The contract is
     * exactly the same as for the standard Quartz execute method.
     *
     * @param context
     * @see #execute
     */
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        JobKey jobKey = context.getTrigger().getJobKey();
        String jobName = jobKey.getName();
        String group = jobKey.getGroup();
        //初始化监控数据
        String processId = insertProcessInfo(jobName, group);
        boolean state = true;
        String runMsg = "";
        try {
            //执行定时任务
            doJob(context);
        } catch (Exception e) {
            log.error("定时任务执行失败：", e);
            state = false;
            runMsg = e.getMessage() + "\n" + ExceptionUtils.getStackTrace(e);
        }
        //更新监控记录
        updateProcessInfo(processId, state, runMsg);
    }

    /**
     * 执行业务操作
     *
     * @param context
     * @throws JobExecutionException
     */
    protected abstract void doJob(JobExecutionContext context);

    /**
     * 更新定时任务执行状态
     *
     * @param processId
     * @param state
     * @param runMsg
     */
    private void updateProcessInfo(String processId, boolean state, String runMsg) {
        String runningState = state ? "1" : "2";
        monitorMapper.updateProcessInfo(processId, runningState, runMsg);
    }

    /**
     * 初始化监控数据
     *
     * @param jobName
     * @param group
     * @return
     */
    private String insertProcessInfo(String jobName, String group) {
        String processId = UUIDUtils.getUUID();
        monitorMapper.insertProcessInfo(processId, jobName, group);
        return processId;
    }
}
